<template>
  <div class="app-container">
    <el-card class="box-card" shadow="false">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="流程名称" prop="processName">
          <el-input v-model="queryParams.processName" placeholder="请输入流程名称" clearable size="small"
            @keyup.enter.native="handleQuery" />
            
        </el-form-item>
        <el-form-item label="流程分类" prop="category">
          <el-select v-model="queryParams.category" clearable placeholder="请选择" size="small">
            <el-option v-for="item in categoryOptions" :key="item.categoryId" :label="item.categoryName"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <!-- <el-col :span="1.5">
          <el-button type="primary" size="mini" @click="handleStartProgress">发起自定义流程</el-button>
        </el-col> -->
        <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          v-hasPermi="['workflow:process:startExport']"
          @click="handleExport"
        >导出</el-button>
      </el-col> -->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" fit :data="processList" border>
        <el-table-column label="序号" type="index" align="center" width="50"></el-table-column>
        <el-table-column label="流程名称" align="left" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-button type="text" @click="handleProcessView(scope.row)">
              <span>{{ scope.row.processName }}</span>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="流程分类" align="center" prop="categoryName" :formatter="categoryFormat" />
        <el-table-column label="流程版本" align="center" v-if="false">
          <template slot-scope="scope">
            <el-tag size="medium">v{{ scope.row.version }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-tag type="success" v-if="!scope.row.suspended">激活</el-tag>
            <el-tag type="warning" v-if="scope.row.suspended">挂起</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="部署时间" align="center" prop="deploymentTime" width="180" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" size="mini" icon="el-icon-video-play" @click="handleStart(scope.row)"
              v-hasPermi="['workflow:process:start']">发起</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />

      <!-- 流程图 -->
      <el-dialog :title="processView.title" :visible.sync="processView.open" width="70%" append-to-body>
        <process-viewer :key="`designer-${processView.index}`" :xml="processView.xmlData" :style="{ height: '400px' }" />
      </el-dialog>
      <!-- <el-dialog title="发起流程" fullscreen :visible.sync="create.open" :before-close="handlecreateDialogClose"
        custom-class="createDialog">
        <el-steps :active="active">
          <el-step title="表单信息"></el-step>
          <el-step title="流程配置"></el-step>
        </el-steps>
        <div v-if="active === 1">
          <el-form ref="form" :model="form" label-width="120px" style="width: 50%;" :rules="rules">
            <el-form-item label="流程名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入流程名称"></el-input>
            </el-form-item>
            <el-form-item label="流程内容" prop="content">
              <Editor v-model="form.content" :min-height="300" />
            </el-form-item>
            <el-form-item label="上传附件" prop="file">
              <el-upload class="upload-demo" :action="uploadImgUrl" :headers="headers" :file-list="form.fileList"
                :before-upload="beforeUpload" :on-success="uploadSuccess" :on-remove="uploadRemove">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
        <div v-if="active === 2">
          <process-designer  style="border: 1px solid rgba(0, 0, 0, 0.1)" ref="modelDesigner"
        appId="1802978559177719809" v-loading="designerData.loading" :bpmnXml="designerData.bpmnXml"
        :designerForm="designerData.form" @save="onSaveDesigner" />
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handlecreateDialogClose"> {{ active === 1 ? '取 消' : '上一步' }}</el-button>
          <el-button type="primary" @click="handlecreateDialogSubmit"> {{ active === 1 ? '下一步' : '提交流程' }}</el-button>
        </span>
      </el-dialog> -->
    </el-card>
  </div>
</template>

<script>
import { listProcess, getBpmnXml } from "@/api/workflow/process";
import { listAllCategory } from '@/api/workflow/category'
import ProcessViewer from '@/components/ProcessViewer'
import Editor from "@/components/Editor";
import { getToken } from "@/utils/auth";
import ProcessDesigner from "@/components/ProcessDesigner";
import SelectUserTable from "@/components/selectUserTable";
import { getTaskCandidate, getTagList, saveTagList } from '@/api/workflow/model.js'

export default {
  name: 'WorkProcess',
  components: {
    ProcessViewer,
    Editor,
    ProcessDesigner,
    SelectUserTable
  },
  data() {
    return {
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/system/oss/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 遮罩层
      loading: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        processKey: undefined,
        processName: undefined,
        category: undefined
      },
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      filterCategoryText: '',
      categoryOptions: [],
      categoryProps: {
        label: 'categoryName',
        value: 'code'
      },
      // 流程定义表格数据
      processList: [],
      processView: {
        title: '',
        open: false,
        index: undefined,
        xmlData: "",
      },
      create: {
        open: false,
      },
      form: {
        name: '',
        fileList: []
      },
      rules: {
        name: [
          { required: true, message: '请输入流程名称', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入流程内容', trigger: 'blur' },
        ],
      },
      active: 1,
      designerData:{
        loading:false,
        bpmnXml:'',
        form: {
          processName: '员工调岗',
          processKey: 'Process_1719199693969',
        },
      },
    }
  },
  created() {
    this.getCategoryList();
    this.getList();
  },
  methods: {
    handlecreateDialogSubmit() {
      if (this.active === 1) {
        this.active = 2
        return
      } else {
        this.create.open = false
        this.active = 1
        return
      }
    },
    handlecreateDialogClose() {
      if (this.active === 1) {
        this.create.open = false
        return
      } else {
        this.active = 1
        return
      }

    },
    // 文件上传前置
    beforeUpload(file) {
      const isLt = file.size / 1024 / 1024 < 10;
      if (!isLt) {
        this.$modal.msgError(`上传文件大小不能超过 ${"10"} MB!`);
        return false;
      }
      this.$modal.loading("正在上传，请稍候...");
    },
    // 删除文件
    uploadRemove(file, fileList) {
      this.form.fileList = fileList;
    },
    // 文件上传成功
    uploadSuccess(response, file, fileList) {
      this.$modal.closeLoading();
      if (response.code === 200) {
        fileList.forEach((item, index) => {
          if (item.uid === file.uid) {
            const fileRes = {
              name: response.data.fileName,
              url: response.data.url,
              format: file.raw?.type,
              size: file.size,
            };
            this.$set(this.form.fileList, index, fileRes);
          }
        });
      } else {
        this.$$message.error(res.msg);
      }
    },
    // 发起空流程 
    handleStartProgress() {
      this.create.open = true
    },
    /** 查询流程分类列表 */
    getCategoryList() {
      listAllCategory().then(response => this.categoryOptions = response.data)
    },
    /** 查询流程定义列表 */
    getList() {
      this.loading = true;
      listProcess(this.queryParams).then(response => {
        this.processList = response.rows;
        this.total = response.total;
        this.loading = false
      })
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查看流程图 */
    handleProcessView(row) {
      let definitionId = row.definitionId;
      this.processView.title = "流程图";
      this.processView.index = definitionId;
      // 发送请求，获取xml
      getBpmnXml(definitionId).then(res => {
        this.processView.xmlData = res.data;
      })
      this.processView.open = true;
    },
    handleStart(row) {
      this.$router.push({
        path: '/workflow/process/start/' + row.deploymentId,
        query: {
          definitionId: row.definitionId,
        }
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('workflow/process/startExport', {
        ...this.queryParams
      }, `wf_start_process_${new Date().getTime()}.xlsx`)
    },
    categoryFormat(row, column) {
      return this.categoryOptions.find(k => k.code === row.category)?.categoryName ?? '';
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .createDialog {
  display: flex;
  flex-direction: column;
  height: 100vh;

  .el-dialog__header {
    height: 54px;
  }

  .el-dialog__body {
    flex: 1;
    overflow-y: auto;

    .el-steps {
      width: 100%;
      padding: 0 25% 20px 25%;
    }
  }

  .el-dialog__footer {
    height: 66px;
  }
}
</style>
